package com.wfs.suanfa.nio.xiaoliu.nio1;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * 客户端
 */
public class SocketChannelDemo {
    public static void main(String[] args) {
        try {
            SocketChannel socketChannel = SocketChannel.open();
            // 发起连接，连接到本机的 EchoServer
            socketChannel.connect(new InetSocketAddress("127.0.0.1", 9999));
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            byteBuffer.put("hello word".getBytes());
            // 接下来需要将buffer中的数据读取到channel内，其实底层是 socket 缓冲区..
            // 所以需要将buffer从写模式切换到读模式
            byteBuffer.flip();
            socketChannel.write(byteBuffer);
            ByteBuffer echoBuffer = ByteBuffer.allocate(1024);
            socketChannel.read(echoBuffer);

            System.out.println("服务器响应:"+new String(echoBuffer.array()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
